package com.leve.admin.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

@Component
public class JedisUtil {
    private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
    private static JedisSentinelPool jedisPool = null;

    static {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(Constants.REDIS_MAXTOTAL);

        config.setMaxIdle(Constants.REDIS_MAXIDLE);

        config.setMaxWaitMillis(Constants.REDIS_MAXWAITMILLIS);

        Set<String> sentinels = new HashSet();
        for (String host : Constants.REDIS_SENHOSTS) {
            sentinels.add(host);
        }
        jedisPool = new JedisSentinelPool(Constants.REDIS_CLUSTERNAME, sentinels, config, Constants.REDIS_PASSWORD);
    }

    public static synchronized Jedis getJedis() {
        Jedis jedis = null;
        if (jedisPool != null) {
            try {
                if (jedis == null) {
                    jedis = jedisPool.getResource();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        return jedis;
    }

    public static synchronized void returnResource(Jedis jedis) {
        if ((null != jedis) && (null != jedisPool)) {
            jedisPool.returnResource(jedis);
        }
    }

    public static synchronized void returnBrokenResource(Jedis jedis) {
        if ((null != jedis) && (null != jedisPool)) {
            jedisPool.returnResource(jedis);
        }
    }

    public void expire(String key, int seconds) {
        if (seconds <= 0) {
            return;
        }
        Jedis jedis = getJedis();
        jedis.expire(key, seconds);
        returnResource(jedis);
    }

    public void expire(String key) {
        expire(key, Constants.REDIS_EXPIRE);
    }

    public static void main(String[] args) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            throw new NullPointerException("Jedis is Null");
        }
        try {
            System.out.println(jedis.get("K3"));
        } catch (Exception e) {
            returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
}
